<template>
	<view class="subtitle-root">
		<!-- 字幕显示组件 -->
		<cover-view v-if="subtitleVisible && currentSubtitleText && isActive" class="subtitle-container"
			:style="{fontSize: subtitleSize + 'px', bottom: isFullScreen ? '80rpx' : '80rpx', zIndex: '-1'  }">
			<cover-view class="subtitle-text">{{ currentSubtitleText }}</cover-view>
		</cover-view>

		<!-- 全屏模式控制栏添加字幕按钮 -->
		<div class="fullControls-bottom-right" v-if="isFullScreen">
			<div class="marginRight" @click.stop="toggleSubtitlePanel">
				<text :class="`${platform}-title`" :style="{color: subtitleVisible ? color : '#FFF'}">
					字幕
				</text>
			</div>
		</div>

		<!-- 抽屉式字幕面板 -->
		<view class="drawer-mask" v-if="showSubtitlePanel || showingSearchResult" @click.stop="closeAllPanels"></view>

		<!-- 字幕面板 -->
		<view class="subtitle-drawer" :class="{ 'drawer-open': showSubtitlePanel }"
			:style="{ width: isFullScreen ? '60%' : '85%' }">
			<div class="subtitle-panel">
				<div class="subtitle-header" @click.stop="closeSubtitlePanel">
					<text :class="`${platform}-big-title`">字幕设置</text>
					<text :class="`${platform}-icon`" style="font-size: 36rpx;">×</text>
				</div>

				<!-- 字幕显示开关 -->
				<div class="subtitle-option" @click.stop="toggleSubtitleVisible">
					<text :class="`${platform}-title`">字幕显示</text>
					<text :class="`${platform}-icon`" :style="{color: subtitleVisible ? color : '#FFF'}">
						{{ subtitleVisible ? '&#xe63b;' : '&#xe657;' }}
					</text>
				</div>

				<view class="subtitle-search-title">
					<text :class="`${platform}-title`">可选字幕</text>
					<div class="subtitle-item search-subtitle-btn" @click.stop="handleSearchSubtitles">
						<text :class="`${platform}-title`" style="color: #007aff;">🔍 搜索更多字幕</text>
					</div>
				</view>
				<!-- 字幕选择列表 -->
				<scroll-view show-scrollbar="false" scroll-y="true" style="max-height: 30vh;">
					<div class="subtitle-item" v-if="videoSubtitles && videoSubtitles.length"
						v-for="(item, index) in videoSubtitles" :key="index">
						<div class="subtitle-item-content" @click.stop="selectSubtitle(item)">
							<text :class="`${platform}-title`" style="white-space: normal;width: 80vw;">
								{{ getFileName(item.Path) || `字幕 ${index + 1}` }}
							</text>
							<text :class="`${platform}-icon`" v-if="currentSubtitle.Index === item.Index"
								:style="{color: color}">✓</text>
						</div>
						<div class="subtitle-delete-btn" @click.stop="deleteSubtitle(item.Index)">
							<text :class="`${platform}-icon`" style="color: #ff4d4f;">删除</text>
						</div>
					</div>
					<!-- 无现有字幕时显示提示 -->
					<div class="subtitle-item" v-if="videoSubtitles && videoSubtitles.length === 0">
						<text :class="`${platform}-title`">暂无本地字幕</text>
					</div>
				</scroll-view>

				<!-- 字幕偏移调整 -->
				<div class="subtitle-adjust" @click.stop="">
					<text :class="`${platform}-title`">字幕偏移</text>
					<div class="adjust-buttons">
						<div @click.stop="adjustSubtitleOffset(-0.5)" class="btnBox">
							<text :class="`${platform}-icon`">-0.5s</text>
						</div>
						<text
							:class="`${platform}-title`">{{ subtitleOffset > 0 ? '+' : '' }}{{ subtitleOffset }}s</text>
						<div @click.stop="adjustSubtitleOffset(0.5)" class="btnBox">
							<text :class="`${platform}-icon`">+0.5s</text>
						</div>
					</div>
				</div>

				<!-- 字幕大小调整 -->
				<div class="subtitle-adjust" @click.stop="">
					<text :class="`${platform}-title`">字幕大小</text>
					<div class="adjust-buttons">
						<div @click.stop="adjustSubtitleSize(-1)" class="btnBox">
							<text :class="`${platform}-icon`">A-</text>
						</div>
						<text :class="`${platform}-title`">{{ subtitleSize }}px</text>
						<div @click.stop="adjustSubtitleSize(1)" class="btnBox">
							<text :class="`${platform}-icon`">A+</text>
						</div>
					</div>
				</div>
			</div>
		</view>
		<!-- 搜索字幕结果面板 -->
		<view class="subtitle-drawer search-drawer" :class="{ 'drawer-open': showingSearchResult }"
			:style="{ width: isFullScreen ? '60%' : '85%' }">
			<div class="subtitle-panel">
				<div class="subtitle-header" @click.stop="closeSearchResult">
					<text :class="`${platform}-big-title`">搜索到的字幕</text>
					<text :class="`${platform}-icon`" style="font-size: 36rpx;">×</text>
				</div>

				<div class="subtitle-loading" v-if="loadingSearch">
					<text :class="`${platform}-title`">正在搜索...</text>
				</div>

				<div class="subtitle-list" @click.stop="" v-else>
					<div class="subtitle-item" v-if="searchSubtitlesList.length>0"
						v-for="(item, index) in searchSubtitlesList" :key="index" @click.stop="downloadSubtitle(item)">
						<text :class="`${platform}-title`" style="white-space: normal;width: 70vw;">
							{{ item.Name || `字幕 ${index + 1}` }}
							<text style="font-size: 12px; color: #999;">
								{{ item.Language || '' }} {{ item.Format || '' }}
							</text>
						</text>
						<text :class="`${platform}-icon`" :style="{color: color}">下载</text>
					</div>
					<div class="subtitle-item" v-if="searchSubtitlesList.length === 0">
						<text :class="`${platform}-title`">未找到相关字幕</text>
					</div>
				</div>
			</div>
		</view>
	</view>
</template>

<script>
	import request from '@/common/request'
	export default {
		props: {
			// 当前是否为活跃状态（当前播放的视频）
			isActive: {
				type: Boolean,
				default: false
			},
			// 视频字幕列表
			videoSubtitles: {
				type: Array,
				default: () => []
			},
			// 视频ID
			videoId: {
				type: String,
				default: ''
			},
			// 媒体源ID
			mediaSourceId: {
				type: String,
				default: ''
			},
			// 是否全屏
			isFullScreen: {
				type: Boolean,
				default: false
			},
			// 平台类型
			platform: {
				type: String,
				default: "android"
			},
			// 主题色
			color: {
				type: String,
				default: "#FF6022"
			}
		},
		watch: {
			// 当切换字幕时保存偏移设置
			currentSubtitle: {
				handler(newVal, oldVal) {
					if (oldVal.SubtitleUrl) {
						// 保存旧字幕的偏移设置
						this.offsetSettings[oldVal.SubtitleUrl] = this.subtitleOffset;
					}
					// 恢复新字幕的偏移设置
					if (newVal.SubtitleUrl && this.offsetSettings[newVal.SubtitleUrl] !== undefined) {
						this.subtitleOffset = this.offsetSettings[newVal.SubtitleUrl];
					} else {
						this.subtitleOffset = 0; // 默认为0
					}
				}
			}
		},
		data() {
			return {
				showSubtitlePanel: false, // 字幕面板显示状态
				currentSubtitle: {}, // 当前选中字幕
				subtitleVisible: true, // 字幕是否可见
				subtitleOffset: 0, // 字幕时间偏移（秒）
				subtitleSize: 16, // 字幕大小（px）
				currentSubtitleText: '', // 当前显示的字幕文本
				parsedSubtitles: [], // 解析后的字幕数组
				loadingSubtitle: false, // 字幕加载状态
				subtitleCache: {}, // 缓存已解析的字幕
				searchSubtitlesList: [], // 搜索到的字幕列表
				showingSearchResult: false, // 是否显示搜索结果面板
				loadingSearch: false, // 搜索加载状态
				lastSubtitleIndex: 0, // 上次字幕索引，用于优化查找
				maxCacheSize: 5, // 最多缓存5个字幕文件
				offsetSettings: {} // 保存不同字幕的偏移设置
			}
		},
		methods: {
			closeAllPanels() {
				this.showSubtitlePanel = false;
				this.showingSearchResult = false;
			},
			// 搜索字幕
			async handleSearchSubtitles() {
				if (!this.videoId || !this.mediaSourceId) return;

				this.showingSearchResult = true;
				this.loadingSearch = true;
				try {
					const res = await this.querySubTitle({
						id: this.videoId,
						MediaSourceId: this.mediaSourceId
					});
					this.searchSubtitlesList = res || [];
				} catch (err) {
					console.error('搜索字幕失败', err);
					uni.showToast({
						title: '搜索字幕失败',
						icon: 'none'
					});
				} finally {
					this.loadingSearch = false;
				}
			},

			// 下载选中的字幕
			async downloadSubtitle(subtitle) {
				if (!this.videoId || !this.mediaSourceId) return;

				try {
					uni.showLoading({
						title: '下载中...'
					});
					await this.downSubtitleToServer({
						id: this.videoId,
						MediaSourceId: this.mediaSourceId,
						SubtitleId: subtitle.Id
					});

					// 通知父组件刷新字幕列表
					this.$emit('refresh-subtitles');
					this.showingSearchResult = false;
					uni.showToast({
						title: '字幕下载成功'
					});
				} catch (err) {
					console.error('下载字幕失败', err);
					uni.showToast({
						title: '下载失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 删除已存在的字幕
			async deleteSubtitle(subtitleIndex) {
				if (!this.videoId || !this.mediaSourceId) return;

				const localIndex = this.videoSubtitles.findIndex(item => item.Index === subtitleIndex);
				if (localIndex === -1) {
					console.warn('未找到要删除的字幕项');
					return;
				}

				uni.showModal({
					title: '确认删除',
					content: '确定要删除该字幕吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.delSubtitleToServer({
									id: this.videoId,
									MediaSourceId: this.mediaSourceId,
									SubtitleIndex: subtitleIndex
								});

								// 通知父组件刷新字幕列表
								this.$emit('refresh-subtitles');
								uni.showToast({
									title: '删除成功'
								});
							} catch (err) {
								console.error('删除字幕失败', err);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			getFileName(path) {
				if (!path) return '';
				const lastIndex = path.lastIndexOf('/');
				return lastIndex === -1 ? path : path.slice(lastIndex + 1);
			},

			// 切换字幕面板显示状态
			toggleSubtitlePanel() {
				this.showSubtitlePanel = !this.showSubtitlePanel;
				this.showingSearchResult = false;
			},

			// 关闭字幕面板
			closeSubtitlePanel() {
				this.showSubtitlePanel = false;
			},

			// 关闭搜索结果面板
			closeSearchResult() {
				this.showingSearchResult = false;
			},

			// 选择字幕
			selectSubtitle(subtitle) {
				this.showSubtitlePanel = false;
				this.showingSearchResult = false;
				this.currentSubtitle = subtitle;
				// 如果有缓存直接使用
				if (this.subtitleCache[subtitle.SubtitleUrl]) {
					this.parsedSubtitles = this.subtitleCache[subtitle.SubtitleUrl];
					return;
				}

				// 加载新字幕
				if (subtitle.SubtitleUrl) {
					this.loadSubtitleFile(subtitle.SubtitleUrl);
				}
			},
			// 优化缓存添加方法
			addToCache(url, subtitles) {
				// 检查缓存是否超过上限
				const cacheKeys = Object.keys(this.subtitleCache);
				if (cacheKeys.length >= this.maxCacheSize) {
					// 移除最早的缓存
					const oldestKey = cacheKeys[0];
					delete this.subtitleCache[oldestKey];
				}
				this.subtitleCache[url] = subtitles;
			},
			// 在subtitle.vue的loadSubtitleFile方法中优化
			loadSubtitleFile(url) {
				// 防止重复加载
				if (this.loadingSubtitle) return;

				this.loadingSubtitle = true;
				// 超时处理
				const timeoutTimer = setTimeout(() => {
					if (this.loadingSubtitle) {
						this.loadingSubtitle = false;
						uni.showToast({
							title: '字幕加载超时',
							icon: 'none',
							duration: 2000
						});
					}
				}, 10000); // 10秒超时

				uni.request({
					url: url,
					timeout: 10000,
					success: (res) => {
						clearTimeout(timeoutTimer);
						let content = res.data;
						if (content.startsWith('\ufeff')) {
							content = content.slice(1); // 移除UTF-8 BOM
						}
						this.parseSubtitle(content);
						this.addToCache(url, this.parsedSubtitles);
						this.loadingSubtitle = false;
					},
					fail: (err) => {
						clearTimeout(timeoutTimer);
						console.error('加载字幕失败', err);
						this.loadingSubtitle = false;
						uni.showToast({
							title: '字幕加载失败，点击重试',
							icon: 'none',
							duration: 3000
						});
						// 提供重试机制
						this.failedSubtitleUrl = url; // 保存失败的URL
					}
				});
			},

			// 新增重试方法
			retryLoadSubtitle() {
				if (this.failedSubtitleUrl) {
					this.loadSubtitleFile(this.failedSubtitleUrl);
				}
			},
			// 解析字幕内容
			parseSubtitle(content) {
				if (!content) {
					this.parsedSubtitles = [];
					return;
				}

				const isVtt = content.trim().startsWith('WEBVTT');
				const isAss = content.includes(
						'Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text') &&
					content.includes('[Events]');
				let lines = content.split(/\r?\n/).filter(line => line !== '');
				let parsedSubtitles = [];

				if (isAss) {
					parsedSubtitles = this.parseAssSubtitle(lines);
				} else if (isVtt) {
					lines = lines.slice(1);
					let index = 0;
					const totalLines = lines.length;

					while (index < totalLines) {
						let timeLine = lines[index];
						if (!timeLine.includes('-->')) {
							index++;
							continue;
						}

						const [startTimeStr, endTimeStr] = timeLine.split('-->').map(t => t.trim());
						const startTime = this.timeToSeconds(startTimeStr);
						const endTime = this.timeToSeconds(endTimeStr);

						index++;
						let textLines = [];
						while (index < totalLines && !lines[index].includes('-->')) {
							textLines.push(lines[index].trim());
							index++;
						}
						const text = textLines.join('\n');

						if (startTime !== null && endTime !== null && text) {
							parsedSubtitles.push({
								startTime,
								endTime,
								text
							});
						}
					}
				} else {
					let index = 0;
					const totalLines = lines.length;

					while (index < totalLines) {
						if (!/^\d+$/.test(lines[index].trim())) {
							index++;
							continue;
						}
						index++;

						if (index >= totalLines) break;
						const timeLine = lines[index].trim();
						if (!timeLine.includes('-->')) {
							index++;
							continue;
						}
						const [startTimeStr, endTimeStr] = timeLine.replace(/,/g, '.').split('-->').map(t => t.trim());
						const startTime = this.timeToSeconds(startTimeStr);
						const endTime = this.timeToSeconds(endTimeStr);
						index++;

						let textLines = [];
						while (index < totalLines && !/^\d+$/.test(lines[index].trim())) {
							textLines.push(lines[index].trim());
							index++;
						}
						const text = textLines.join('\n');

						if (startTime !== null && endTime !== null && text) {
							parsedSubtitles.push({
								startTime,
								endTime,
								text
							});
						}
					}
				}

				parsedSubtitles.sort((a, b) => a.startTime - b.startTime);
				this.parsedSubtitles = parsedSubtitles;
			},

			// 解析ASS字幕
			parseAssSubtitle(lines) {
				const subtitles = [];
				let inEvents = false;
				let formatIndices = {};

				for (const line of lines) {
					const trimmedLine = line.trim();

					if (trimmedLine === '[Events]') {
						inEvents = true;
						continue;
					}

					if (inEvents && trimmedLine.startsWith('Format:')) {
						const formatParts = trimmedLine.replace('Format:', '').trim().split(',');
						formatParts.forEach((part, index) => {
							formatIndices[part.trim()] = index;
						});
						continue;
					}

					if (inEvents && trimmedLine.startsWith('Dialogue:')) {
						const dialogueParts = trimmedLine.replace('Dialogue:', '').split(',');

						const startTimeStr = dialogueParts[formatIndices.Start]?.trim();
						const endTimeStr = dialogueParts[formatIndices.End]?.trim();

						const textStartIndex = formatIndices.Text;
						const textParts = dialogueParts.slice(textStartIndex);
						let text = textParts.join(',').trim();

						text = text.replace(/\{[^}]+\}/g, '');
						text = text.replace(/\\N/g, '\n');

						const startTime = this.assTimeToSeconds(startTimeStr);
						const endTime = this.assTimeToSeconds(endTimeStr);

						if (startTime !== null && endTime !== null && text) {
							subtitles.push({
								startTime,
								endTime,
								text
							});
						}
					}
				}

				return subtitles;
			},

			// ASS时间转换
			assTimeToSeconds(timeStr) {
				if (!timeStr) return null;

				const parts = timeStr.split(':').map(part => part.trim());
				let hours = 0,
					minutes = 0,
					seconds = 0,
					milliseconds = 0;

				if (parts.length === 3) {
					const [hours, minutes, secWithMs] = parts;
					const [sec, ms] = secWithMs.split('.').map(Number);
					seconds = Number(sec);
					milliseconds = ms || 0;
				} else if (parts.length === 2) {
					const [minutes, secWithMs] = parts;
					const [sec, ms] = secWithMs.split('.').map(Number);
					seconds = Number(sec);
					milliseconds = ms || 0;
				} else {
					return null;
				}

				return Number((Number(hours) * 3600 + Number(minutes) * 60 + seconds + milliseconds / 100).toFixed(3));
			},

			// 时间转换为秒
			timeToSeconds(timeStr) {
				const parts = timeStr.split(':').map(part => part.trim());
				let seconds = 0;
				let milliseconds = 0;

				if (parts.length === 3) {
					const [hours, minutes, secWithMs] = parts;
					const [sec, ms] = secWithMs.split('.').map(Number);
					seconds = Number(hours) * 3600 + Number(minutes) * 60 + Number(sec);
					milliseconds = ms || 0;
				} else if (parts.length === 2) {
					const [minutes, secWithMs] = parts;
					const [sec, ms] = secWithMs.split('.').map(Number);
					seconds = Number(minutes) * 60 + Number(sec);
					milliseconds = ms || 0;
				} else if (parts.length === 1) {
					const [secWithMs] = parts;
					const [sec, ms] = secWithMs.split('.').map(Number);
					seconds = Number(sec);
					milliseconds = ms || 0;
				} else {
					return null;
				}

				return Number((seconds + milliseconds / 1000).toFixed(3));
			},

			// 在subtitle.vue的updateCurrentSubtitle方法中优化
			updateCurrentSubtitle(currentTime) {
				if (!this.subtitleVisible || !this.parsedSubtitles || this.parsedSubtitles.length === 0 || !this
					.isActive) {
					this.currentSubtitleText = '';
					return;
				}

				const timeWithOffset = currentTime + this.subtitleOffset;
				let currentSub = null;
				let startSearchIndex = 0;

				// 优化1：根据时间戳智能选择搜索起点
				if (this.lastSubtitleIndex !== undefined) {
					// 如果当前时间大于上次字幕结束时间，从下一个开始找
					if (timeWithOffset > this.parsedSubtitles[this.lastSubtitleIndex]?.endTime) {
						startSearchIndex = this.lastSubtitleIndex + 1;
					} else if (timeWithOffset < this.parsedSubtitles[this.lastSubtitleIndex]?.startTime) {
						// 如果当前时间小于上次字幕开始时间，从头开始找（处理回退情况）
						startSearchIndex = 0;
					} else {
						startSearchIndex = this.lastSubtitleIndex;
					}
				}

				// 优化2：限制搜索范围，提高性能
				const searchEnd = Math.min(startSearchIndex + 10, this.parsedSubtitles.length);
				for (let i = startSearchIndex; i < searchEnd; i++) {
					if (timeWithOffset >= this.parsedSubtitles[i].startTime && timeWithOffset <= this.parsedSubtitles[i]
						.endTime) {
						currentSub = this.parsedSubtitles[i];
						this.lastSubtitleIndex = i;
						break;
					}
				}

				// 优化3：如果在范围内没找到，扩大搜索范围
				if (!currentSub) {
					for (let i = 0; i < this.parsedSubtitles.length; i++) {
						if (timeWithOffset >= this.parsedSubtitles[i].startTime && timeWithOffset <= this.parsedSubtitles[
								i].endTime) {
							currentSub = this.parsedSubtitles[i];
							this.lastSubtitleIndex = i;
							break;
						}
					}
				}

				this.currentSubtitleText = currentSub ? currentSub.text : '';
			},
			// 切换字幕显示/隐藏
			toggleSubtitleVisible() {
				this.subtitleVisible = !this.subtitleVisible;
			},

			// 调整字幕偏移
			adjustSubtitleOffset(seconds) {
				this.subtitleOffset += seconds;
			},

			// 调整字幕大小
			adjustSubtitleSize(change) {
				this.subtitleSize = Math.max(12, Math.min(24, this.subtitleSize + change));
			},

			// 外部调用：加载字幕
			loadSubtitles(subtitle) {
				if (!subtitle) {
					this.parsedSubtitles = [];
					this.currentSubtitleText = '';
					return;
				}

				if (this.subtitleCache[subtitle.SubtitleUrl]) {
					this.parsedSubtitles = this.subtitleCache[subtitle.SubtitleUrl];
					this.currentSubtitle = subtitle;
					return;
				}

				this.selectSubtitle(subtitle);
			},
			/**
			 * 查询字幕
			 * @param {Object} id
			 * @param {Object} MediaSourceId
			 */
			async querySubTitle(queryBody) {
				let {
					id,
					MediaSourceId
				} = queryBody;
				let getJSON = {
					MediaSourceId: MediaSourceId
				}
				let urlAppend = this.jsonToGetParams(getJSON)
				return request.get(`/emby/Items/${id}/RemoteSearch/Subtitles/zh-CN${urlAppend}`)
			},
			/** 下载字幕到服务器，下载成功后，再次请求getVideoPlayback获取新的字幕信息，然后再选择
			 * @param {Object} id
			 * @param {Object} MediaSourceId
			 * @param {Object} SubtitleId
			 */
			async downSubtitleToServer(queryBody) {
				let {
					id,
					MediaSourceId,
					SubtitleId
				} = queryBody;
				let getJSON = {
					MediaSourceId: MediaSourceId
				}
				let urlAppend = this.jsonToGetParams(getJSON)
				return request.post(`/emby/Items/${id}/RemoteSearch/Subtitles/${SubtitleId}${urlAppend}`)
			},
			/** 删除字幕数据
			 * @param {Object} id
			 * @param {Object} MediaSourceId
			 * @param {Object} SubtitleIndex 字幕信息的Index字段
			 */
			async delSubtitleToServer(queryBody) {
				let {
					id,
					MediaSourceId,
					SubtitleIndex
				} = queryBody;
				let getJSON = {
					MediaSourceId: MediaSourceId
				}
				let urlAppend = this.jsonToGetParams(getJSON)
				return request.post(`/emby/Videos/${id}/Subtitles/${SubtitleIndex}/Delete${urlAppend}`)
			},
			jsonToGetParams(json) {
				// 处理空对象
				if (!json || Object.keys(json).length === 0) {
					return '';
				}
				const params = [];
				for (const key in json) {
					if (json.hasOwnProperty(key)) {
						const value = json[key];
						// 只排除空字符串、undefined、null
						if (value !== '' && value !== undefined && value !== null) {
							params.push(`${key}=${value}`);
						}
					}
				}
				return params.length > 0 ? `?${params.join('&')}` : '';
			}

		}
	}
</script>

<style>
	@import "./android.scss";
	@import "./ios.scss";
	@font-face {
		font-family: "texticons";
		src: url('/static/chunlei-video/text-icon.ttf') format('truetype');
	}
	.subtitle-panel {
		position: relative;
		background-color: rgba(0, 0, 0, 0.8);
		border-top-left-radius: 16rpx;
		border-top-right-radius: 16rpx;
		padding: 20rpx;
		backdrop-filter: blur(8px);
		-webkit-backdrop-filter: blur(8px);
		z-index: 999;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		width: 100vw;
		height: 90vh;
		border-radius: 8px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
	}

	/* 选项标题 - 区分分类 */
	.subtitle-panel text:not(.subtitle-header text):first-of-type {
		font-size: 28rpx;
		color: #bbbbbb;
		/* 次级标题用浅灰，区分主内容 */
		margin: 24rpx 0 12rpx;
		display: block;
	}

	.subtitle-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12rpx 0 24rpx;
		margin-bottom: 12rpx;
		border-bottom: 1px solid rgba(255, 255, 255, 0.1);
	}

	.subtitle-header text:first-child {
		font-size: 34rpx;
		font-weight: 600;
		color: #ffffff;
		/* 标题用纯白色，增强醒目度 */
	}

	.subtitle-header text:last-child {
		font-size: 36rpx;
		color: #cccccc;
		/* 关闭按钮用浅灰，降低视觉权重 */
		transition: color 0.2s;
	}

	.subtitle-header text:last-child:active {
		color: #ffffff;
		/* 点击时变白，增强反馈 */
	}

	.subtitle-option {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 8rpx;
		/* 加大内边距，提升点击体验 */
		border-bottom: 1px solid rgba(255, 255, 255, 0.05);
		/* 淡色分隔线，减少视觉干扰 */
		transition: background-color 0.2s;
	}

	.subtitle-option:active,
	.subtitle-adjust:active {
		background-color: rgba(255, 255, 255, 0.05);
		/* 点击时的背景反馈 */
	}

	/* 文本样式 - 优化对比度 */
	.subtitle-option text:first-child,
	.subtitle-adjust text:first-child,
	.subtitle-item text:first-child {
		font-size: 30rpx;
		color: #f0f0f0;
		/* 主文本用近白色，确保在深色背景上清晰 */
	}

	/* 右侧操作文本 - 次要信息弱化 */
	.subtitle-option text:last-child,
	.adjust-buttons text {
		font-size: 28rpx;
		color: #b0b0b0;
		/* 次要文本用中灰，区分主次 */
	}

	.subtitle-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 8rpx;
		border-bottom: 1px solid rgba(255, 255, 255, 0.05);
		transition: background-color 0.2s;
	}

	.subtitle-item.selected {
		background-color: rgba(255, 255, 255, 0.08);
		/* 选中项背景高亮 */
	}

	.subtitle-item:active {
		background-color: rgba(255, 255, 255, 0.05);
	}

	.subtitle-item.selected text:first-child {
		color: #409eff;
		/* 选中项文本用主题色，增强识别度 */
		font-weight: 500;
	}

	.subtitle-item.selected text:last-child {
		color: #409eff;
		/* 选中标记同步主题色 */
	}

	.subtitle-adjust {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 8rpx;
		/* 加大内边距，提升点击体验 */
		border-bottom: 1px solid rgba(255, 255, 255, 0.05);
		/* 淡色分隔线，减少视觉干扰 */
		transition: background-color 0.2s;
	}

	.adjust-buttons {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.adjust-buttons .btnBox {
		padding: 8rpx 16rpx;
		background-color: rgba(255, 255, 255, 0.1);
		border-radius: 6rpx;
		transition: background-color 0.2s;
	}

	.adjust-buttons .btnBox:active {
		background-color: rgba(255, 255, 255, 0.2);
		/* 按钮点击反馈 */
	}

	/* 无字幕提示 - 弱化但清晰 */
	.subtitle-item:only-child text {
		color: #999999;
		font-style: italic;
		/* 斜体区分普通项 */
	}

	/* 字幕样式 */
	.subtitle-container {
		position: absolute;
		width: 100%;
		display: flex;
		justify-content: center;
		z-index: 10;
		pointer-events: none;
		/* 避免遮挡视频点击事件 */
	}

	.subtitle-item-content {
		flex: 1;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.subtitle-delete-btn {
		margin-left: 20rpx;
		color: #ff4d4f;
	}

	.subtitle-loading {
		padding: 30rpx;
		text-align: center;
	}

	/* 处理ASS可能的上下字幕位置 */
	.subtitle-container.top {
		bottom: auto;
		top: 180rpx;
	}

	.subtitle-container.bottom {
		bottom: 180rpx;
		top: auto;
	}

	.subtitle-text {
		color: white;
		text-shadow: 0 0 2px black, 0 0 4px black;
		text-align: center;
		max-width: 98%;
		word-wrap: break-word;
		padding: 8rpx 16rpx;
		/* background-color: rgba(0, 0, 0, 0.3); */
		border-radius: 8rpx;
		line-height: 1.5;
		/* 优化多行字幕行高 */
		white-space: pre-line;
		/* 保留ASS中的换行符 */
		transition: opacity 0.3s;
		/* 平滑显示/隐藏过渡 */
	}

	.subtitle-search-title {
		display: flex;
		flex-flow: row;
		align-items: center;
		justify-content: space-between;
		padding: 10px 3px;
	}


	/* 竖屏模式优化（假设竖屏宽度 < 768px） */
	@media (max-width: 767px) {
		.subtitle-panel {
			padding: 24rpx;
		}

		.subtitle-option,
		.subtitle-item,
		.subtitle-adjust {
			padding: 20rpx 6rpx;
		}

		.subtitle-header text:first-child {
			font-size: 30rpx;
		}
	}

	/* 全屏横屏模式优化 */
	.fullscreen .subtitle-panel {
		border-radius: 0;
		/* 全屏时去掉圆角，利用完整屏幕空间 */
		padding: 40rpx 60rpx;
		/* 横屏时加大左右边距 */
	}

	.search-subtitle-btn {
		margin-top: 15rpx;
		padding-top: 15rpx;
	}

	.search-subtitle-btn .android-title,
	.search-subtitle-btn .ios-title {
		color: #007aff !important;
		/* 使用系统主题色突出显示 */
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 新增抽屉相关样式 */
	.drawer-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 998;
		transition: opacity 0.3s;
	}

	.subtitle-drawer {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.8);
		z-index: 999;
		transform: translateX(100%);
		transition: transform 0.3s ease-out;
		box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3);
	}

	.search-drawer {
		z-index: 1000;
		/* 搜索抽屉在主抽屉上方 */
	}

	.drawer-open {
		transform: translateX(0);
	}

	/* 全屏模式优化 */
	.fullscreen .subtitle-drawer {
		width: 50%;
	}

	/* 竖屏模式优化 */
	@media (max-width: 767px) {
		.subtitle-drawer {
			width: 100% !important;
		}
	}
</style>